package org.wyw.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtil {

    public static void toZip(List<File> srcFiles, File zipFile) throws Exception {
        long start = System.currentTimeMillis();
        if (zipFile == null) {
//            log.error("压缩文件是null");
            return;
        }
        if(!zipFile.getName().endsWith(".zip")){
//            log.error("压缩文件后缀异常：zipfile={}",zipFile.getPath());
            return;
        }
        if(!zipFile.exists()){
//            log.info("压缩文件不存在，先创建");
            zipFile.createNewFile();
        }
        ZipOutputStream out = null;
        try {
            out = new ZipOutputStream(new FileOutputStream(zipFile));
            for(int i=0;i<srcFiles.size();i++){
                File inFile = srcFiles.get(i);
                if(inFile.exists()){
                    ZipEntry entry = new ZipEntry(inFile.getName());
                    out.putNextEntry(entry);
                    int len =0;
                    byte[] buffer = new byte[1024];
                    FileInputStream fis;
                    fis =new FileInputStream(inFile);
                    while((len = fis.read(buffer))>0){
                        out.write(buffer,0,len);
                        out.flush();
                    }
                    out.closeEntry();
                    fis.close();

                }else{
//                    log.error("文件不存在：{}",inFile.getPath());
                }
            }



            long end = System.currentTimeMillis();
//            log.info("压缩文件耗时：{}ms",(end-start));

        }catch (Exception e){
//            log.error("生成zip文件异常：{}",e.getMessage());
        }finally {
            if(out!=null){
                try {
                    out.close();
                }catch (IOException e){
//                    log.error("ZIPUtil toZip close exception:{}",e.getMessage());
                }
            }
        }





    }
}
